"""基于激活码的用户管理系统数据模型"""
from dataclasses import dataclass, field
from datetime import date, datetime
from typing import Optional, Dict, Any, List
import json
from enum import Enum

class UserRole(Enum):
    """用户角色枚举"""
    SUPER_ADMIN = 'super_admin'
    PROMOTION_ADMIN = 'promotion_admin'
    USER = 'user'

class UserStatus(Enum):
    """用户状态枚举"""
    ACTIVE = 'active'
    INACTIVE = 'inactive'
    SUSPENDED = 'suspended'

class CodeType(Enum):
    """激活码类型枚举"""
    SUPER_ADMIN = 'super_admin'
    PROMOTION_ADMIN = 'promotion_admin'
    USER = 'user'

@dataclass
class User:
    """用户模型（简化版）"""
    id: Optional[int] = None
    username: str = ''
    role: UserRole = UserRole.USER
    status: UserStatus = UserStatus.ACTIVE
    trial_start_date: Optional[date] = None
    trial_end_date: Optional[date] = None
    subscription_start_date: Optional[date] = None
    subscription_end_date: Optional[date] = None
    promotion_admin_id: Optional[int] = None
    activation_code_id: int = 0
    last_login_at: Optional[datetime] = None
    login_count: int = 0
    created_at: Optional[datetime] = None
    updated_at: Optional[datetime] = None

    def to_api_format(self) -> Dict[str, Any]:
        """转换为API格式"""
        return {
            'id': self.id,
            'username': self.username,
            'role': self.role.value,
            'status': self.status.value,
            'trial_start_date': self.trial_start_date.strftime('%Y-%m-%d') if self.trial_start_date else None,
            'trial_end_date': self.trial_end_date.strftime('%Y-%m-%d') if self.trial_end_date else None,
            'subscription_start_date': self.subscription_start_date.strftime('%Y-%m-%d') if self.subscription_start_date else None,
            'subscription_end_date': self.subscription_end_date.strftime('%Y-%m-%d') if self.subscription_end_date else None,
            'promotion_admin_id': self.promotion_admin_id,
            'activation_code_id': self.activation_code_id,
            'last_login_at': self.last_login_at.isoformat() if self.last_login_at else None,
            'login_count': self.login_count,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }

    def is_trial_active(self) -> bool:
        """检查试用期是否有效"""
        if not self.trial_end_date:
            return False
        return datetime.now().date() <= self.trial_end_date

    def is_subscription_active(self) -> bool:
        """检查订阅是否有效"""
        if not self.subscription_end_date:
            return False
        return datetime.now().date() <= self.subscription_end_date

    def is_active_user(self) -> bool:
        """检查用户是否有效"""
        return (self.status == UserStatus.ACTIVE and 
                (self.is_trial_active() or self.is_subscription_active()))

@dataclass
class ActivationCode:
    """激活码模型（核心模型）"""
    id: Optional[int] = None
    code: str = ''
    code_type: CodeType = CodeType.USER
    role: UserRole = UserRole.USER
    trial_days: int = 0
    subscription_days: int = 0
    max_users: int = 1
    created_by: Optional[int] = None
    used_by: Optional[int] = None
    used_at: Optional[datetime] = None
    is_active: bool = True
    expires_at: Optional[datetime] = None
    description: Optional[str] = None
    created_at: Optional[datetime] = None
    updated_at: Optional[datetime] = None

    def to_api_format(self) -> Dict[str, Any]:
        """转换为API格式"""
        return {
            'id': self.id,
            'code': self.code,
            'code_type': self.code_type.value,
            'role': self.role.value,
            'trial_days': self.trial_days,
            'subscription_days': self.subscription_days,
            'max_users': self.max_users,
            'created_by': self.created_by,
            'used_by': self.used_by,
            'used_at': self.used_at.isoformat() if self.used_at else None,
            'is_active': self.is_active,
            'expires_at': self.expires_at.isoformat() if self.expires_at else None,
            'description': self.description,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }

    def is_valid(self) -> bool:
        """检查激活码是否有效"""
        if not self.is_active:
            return False
        
        if self.expires_at and datetime.now() > self.expires_at:
            return False
        
        return True

    def can_create_users(self) -> bool:
        """检查是否可以创建用户（推广管理员功能）"""
        return self.role == UserRole.PROMOTION_ADMIN and self.max_users > 0

@dataclass
class UserActivityLog:
    """用户活动日志模型"""
    id: Optional[int] = None
    user_id: int = 0
    action: str = ''
    target_type: Optional[str] = None
    target_id: Optional[int] = None
    details: Optional[str] = None
    ip_address: Optional[str] = None
    user_agent: Optional[str] = None
    created_at: Optional[datetime] = None

    def to_api_format(self) -> Dict[str, Any]:
        """转换为API格式"""
        return {
            'id': self.id,
            'user_id': self.user_id,
            'action': self.action,
            'target_type': self.target_type,
            'target_id': self.target_id,
            'details': self.details,
            'ip_address': self.ip_address,
            'user_agent': self.user_agent,
            'created_at': self.created_at.isoformat() if self.created_at else None
        }

@dataclass
class ServicePackage:
    """服务套餐模型"""
    id: Optional[int] = None
    name: str = ''
    description: Optional[str] = None
    trial_days: int = 0
    subscription_days: int = 30
    max_users: int = 1
    features: Optional[str] = None
    is_active: bool = True
    created_at: Optional[datetime] = None
    updated_at: Optional[datetime] = None

    def to_api_format(self) -> Dict[str, Any]:
        """转换为API格式"""
        return {
            'id': self.id,
            'name': self.name,
            'description': self.description,
            'trial_days': self.trial_days,
            'subscription_days': self.subscription_days,
            'max_users': self.max_users,
            'features': self.features,
            'is_active': self.is_active,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }
